package com.ycwl.aiLive_2d.ai_model_api.wxChatRobot.service;

import com.alibaba.fastjson.JSONObject;
import com.ycwl.aiLive_2d.ai_model_api.wxChatRobot.url.Url;
import com.ycwl.aiLive_2d.ai_model_api.wxChatRobot.utils.HttpUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author songmingsong
 * @date 2023/6/29
 */
public class Robot {
    private String token;

    private static Map<String, Object> signMap = new HashMap<>();

    public Robot(String token) {
        this.token = token;
        /*
         * 获取Signature
         */
        String signature = getSignature();
        JSONObject jsonObject = JSONObject.parseObject(signature);
        signMap.put("signTime", new Date());
        signMap.put("signature", jsonObject.get("signature"));
        signMap.put("expiresIn", jsonObject.get("expiresIn"));
        signMap.put("rid", jsonObject.get("rid"));
    }

    public String answer(String msg) {
        JSONObject jsonObject = sendMessage(msg);
        return jsonObject.get("answer").toString();
    }

    /**
     * 发送问题，返回结果
     *
     * @param message 问题
     * @return jsonObject字符串
     */
    private JSONObject sendMessage(String message) {
        checkSignature();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("signature", signMap.get("signature"));
        params.put("query", message);
        return JSONObject.parseObject(HttpUtils.sendPost(changeToken(Url.AI_BOT_URL), params));
    }

    /**
     * 检查签名是否过期
     */
    private void checkSignature() {
        Date signTime = (Date) signMap.get("signTime");
        if (signTime.before(new Date())) {
            // 重新获取签名
            getSignature();
        }
    }

    /**
     * 获取签名
     *
     * @return
     */
    private String getSignature() {
        String userid = String.valueOf(Math.random());
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userid", userid);
        return HttpUtils.sendPost(changeToken(Url.SIGN_URL), params);
    }

    /**
     * 转换请求URL
     *
     * @param tokenUrl
     * @return
     */
    private String changeToken(String tokenUrl) {
        return tokenUrl.replace("{TOKEN}", this.token);
    }
}
